package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.core.entity.UserLoginEntity;
import com.recharge.core.entity.UserLoginLogEntity;
import com.recharge.core.mapper.UserLoginLogMapper;
import com.recharge.domain.query.UserLoginLogQueryDO;
import com.recharge.domain.vo.UserLoginLogDO;
import com.recharge.service.UserLoginLogService;
import com.recharge.service.UserService;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 用户登录日志 服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2020-08-24
 */
@Service
public class UserLoginLogServiceImpl extends ServiceImpl<UserLoginLogMapper, UserLoginLogEntity> implements UserLoginLogService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private UserService userService;

    @Override
    public ResultDO add(UserLoginLogDO domain) {

        ResultDO result = userService.isUserExist(domain.getUsername());

        if(result.isSuccess()) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.USER_LOGIN_IS_NO_EXIST);
            return result;
        }

        UserLoginLogEntity entity = new UserLoginLogEntity();

        result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        entity.setLoginTime(Calendar.getInstance().getTime());
        boolean res = false;
        try {
            res = this.save(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.LOG_ADD_LOGIN_ERROR);
            logger.debug("error code：" + ErrorCode.LOG_ADD_LOGIN_ERROR.getCode() + " msg" + ErrorCode.LOG_ADD_LOGIN_ERROR.getMsg());
            return result;
        }

        return result;
    }

    public ResultDO getLoginFailureCount(String userId) {

        ResultDO result = new ResultSupport();
        QueryWrapper<UserLoginLogEntity> queryWrapper = new QueryWrapper<UserLoginLogEntity>();
        Calendar beginTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();
        beginTime.set(beginTime.get(Calendar.YEAR), beginTime.get(Calendar.MONTH), beginTime.get(Calendar.DAY_OF_MONTH - 1), 0, 0, 0);
        endTime.set(endTime.get(Calendar.YEAR), endTime.get(Calendar.MONTH), endTime.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        queryWrapper.like("user_id", userId).between("login_time", beginTime, endTime).eq("status", 0);

        int count = 0;
        try {
            count = this.baseMapper.selectCount(queryWrapper);
        } catch(Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, count);
        return result;
    }


    @Override
    public ResultDO find(UserLoginLogQueryDO query) {
        // 创建实体类
        UserLoginLogEntity entity = new UserLoginLogEntity();
        // 拷贝数据
        ResultDO result = BeanUtilsExtends.copy(entity, query);

        //判断是否拷贝成功
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        // 创建查询器
        QueryWrapper<UserLoginLogEntity> wrapper = new QueryWrapper<>(entity);
        Page<UserLoginLogEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());

        IPage<UserLoginLogEntity> iPage;
        try {
            // 分页查询
            iPage = baseMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        // 获取查询信息
        List<UserLoginLogDO> doList = getDomainList(iPage.getRecords());
        PageDO<UserLoginLogDO> pageDO = new PageDO<>();

        // 设置分页信息
        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    private UserLoginLogDO getDomain(UserLoginLogEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) {
            return null;
        }
        UserLoginLogDO domain = new UserLoginLogDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<UserLoginLogDO> getDomainList(List<UserLoginLogEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<UserLoginLogDO> doList = new ArrayList<UserLoginLogDO>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(UserLoginLogEntity entity : list) {

                UserLoginLogDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
}
